package com.dongrj.framework.web;


import com.dongrj.framework.core.exception.BusinessException;
import com.dongrj.framework.core.exception.SystemException;
import com.dongrj.framework.core.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @author dongrongjun
 * @date 2020/08/04
 * 统一异常处理
 */
@ControllerAdvice
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Result handleBusinessException(BusinessException exception, HttpServletRequest request) {
        return exception(exception, request);
    }

    @ExceptionHandler(SystemException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Result handleSystemException(SystemException exception, HttpServletRequest request) {
        return exception(exception, request);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Result handleException(Exception exception, HttpServletRequest request) {
        return exception(exception, request);
    }

    private Result exception(Exception exception, HttpServletRequest request) {
        String message = exception.getMessage();
        String servletPath = request.getServletPath();
        log.error(String.format("servletPath=%s", servletPath), exception);
        return Result.fail(message);
    }
}
